package controllers;

import play.*;
import play.data.validation.Valid;
import play.db.jpa.JPA;
import play.libs.Codec;
import play.mvc.*;

import java.util.*;

import Tools.CRUD;
import models.*;
/**
 * Application::主控制器，包括用户验证，所有的子控制器必须继承它。
 * 
 * @see BaseModule
 * @since 1.0
 * @author Mr.J.
 * **/
public class Application extends Controller implements BaseModule{

    public static void index() {
    	User user = getCurrutUser();
    	List<Actions> menus = user.actions;
        render(user, menus);
    }
    
    @Before(unless={"login","checkUser"})
    public static void identificaAndPermission(){
    	if(getCurrutUser() == null)
    		login();
    }
    
    public static void login(){
    	render();
    }
    
    public static void checkUser(@Valid User user){
    	if(validation.hasErrors()){
    		params.flash();
    		validation.keep();
    		login();
    	}
    	User u = User.find("name=? AND password=?", user.name, Codec.hexMD5(user.password)).first();
    	if(u != null){
	    	session.put("user_id", u.id);
	    	index();
    	}else{
    		flash("pass_error", "password wrong!");
    		login();
    	}
    }
    
    public static User getCurrutUser(){
    	if(session.get("user_id") != null){
	    	User u = User.findById(Long.valueOf(session.get("user_id")));
	    	return u;
    	}return null;
    }
    
    public static void logout(){
    	session.clear();
    	login();
    }
}